(function (angular) {
  'use strict';
  var dependencies = ['oc.lazyLoad', 'ngResource', 'fs.router', 'fs.constant', 'fs.storage', 'fs.ajax', 'fs.date', 'fs.modal', 'fs.layout', 'fs.menu'];
  angular.module("fs.waf", dependencies).controller("mainController", mainController)
	/*.animation(".fade-in", [ "$animateCss", function($animateCss) {
		return {
			enter : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 0
					},
					to : {
						opacity : 1
					},
					duration : 3
				});
			}
		};
	} ])
	.animation(".fade-out", [ "$animateCss", function($animateCss) {
		return {

			leave : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 1
					},
					to : {
						opacity : 0
					},
					duration : 3
				});
			}
		};
	} ])*/;

  mainController.$inject = ['$rootScope', '$scope', '$window', '$document', '$log', '$translate', '$locale', '$location', '$q', 'Constants', 'ajaxServiceFactory', 'storageService',
    'signonService', '$ocLazyLoad', 'routerService', 'commonService'];
  function mainController($rootScope, $scope, $window, $document, $log, $translate, $locale, $location, $q, Constants, ajaxServiceFactory, storageService, signonService, $ocLazyLoad,
    routerService, commonService) {
    var hadBindKeyDown, watcher, ctrl = this, log = $scope.loggerFactory.getLogger("mainController");
    ctrl.$onInit = function () {
      initApplicationSetting();
      signonService.isAuthenticated().then(
        function () {
          $rootScope.user = storageService.getUserInfo();
          $rootScope.site = storageService.getSiteInfo();
          $rootScope.menus = storageService.getMenuInfo();
          $rootScope.updateTheme();
          $rootScope.initLocaleData();
          $rootScope.initNotificationData();
          $ocLazyLoad.load(
            ['waf/css/' + $scope.app.settings.theme + '/app.css?_v_=' + versionInfo.version,
            'waf/js/' + $scope.app.settings.theme + '/test/testRouter.js?_v_=' + versionInfo.version,
            'cda/js/' + $scope.app.settings.theme + '/router/pageRouter.js?_v_=' + versionInfo.version,
            'cda/js/' + $scope.app.settings.theme + '/router/lookupRouter.js?_v_=' + versionInfo.version,
            'cda/js/' + $scope.app.settings.theme + '/router/popupRouter.js?_v_=' + versionInfo.version,
            'cda/js/' + $scope.app.settings.theme + '/test/testRouter.js?_v_=' + versionInfo.version,
            'cls/js/' + $scope.app.settings.theme + '/router/pageRouter.js?_v_=' + versionInfo.version,
            'cls/js/' + $scope.app.settings.theme + '/router/lookupRouter.js?_v_=' + versionInfo.version,
            'cls/js/' + $scope.app.settings.theme + '/router/popupRouter.js?_v_=' + versionInfo.version,
            'apf/js/' + $scope.app.settings.theme + '/router/pageRouter.js?_v_=' + versionInfo.version,
            'apf/js/' + $scope.app.settings.theme + '/router/lookupRouter.js?_v_=' + versionInfo.version,
            'apf/js/' + $scope.app.settings.theme + '/router/popupRouter.js?_v_=' + versionInfo.version,
            'lfe/js/' + $scope.app.settings.theme + '/router/pageRouter.js?_v_=' + versionInfo.version,
            'lfe/js/' + $scope.app.settings.theme + '/router/lookupRouter.js?_v_=' + versionInfo.version,
            'lfe/js/' + $scope.app.settings.theme + '/router/popupRouter.js?_v_=' + versionInfo.version]
            , {
              cache: true
            }
          ).then(function () {
            if ($location.state()) {
              $scope.go($location.state());
            } else if ($location.url()) {
              $scope.go($location.url().substr(1).split('/').join('.'));
            } else {
              $scope.go(Constants.WELCOME_URL);
            }
          }, function (error) {
            log.error(error);
          });
        },
        function () {
          $scope.go('signon');
        });
    };
    //TODO: change implementation
		/*$rootScope.hasBackdrop = function() {
			var backdrop = $document[0].querySelector('.modal-backdrop');
			if (backdrop && !hadBindKeyDown) {
				$document.bind('keydown', function(event) {
					if (event.keyCode == 9) {
						backdrop.focus();
						event.preventDefault();
						event.stopPropagation();
					}
				});
				hadBindKeyDown = true;
			} else if (!backdrop && hadBindKeyDown) {
				$document.unbind('keydown');
				hadBindKeyDown = false;
			}
			return backdrop ? true : false
		}*/
    angular.element($window).on('resize', function () {
      var header = $document[0].querySelector('.app-header');
      var content = $document[0].querySelector('.app-content');
      var footer = $document[0].querySelector('.app-footer');
      if (header && content && footer) {
        var h = $window.innerHeight - (header.offsetHeight + content.offsetHeight + footer.offsetHeight);
        if (h > 0) {
          angular.element($document[0].querySelector('.app-footer')).css({
            'position': 'absolute'
          });
        } else if (h <= 0) {
          angular.element($document[0].querySelector('.app-footer')).css({
            'position': 'relative'
          });
        }
      }
    });
    //TODO: change implementation
		/*$scope.$watch(function() {
			var header = $document[0].querySelector('.app-header');
			var content = $document[0].querySelector('.app-content');
			var footer = $document[0].querySelector('.app-footer');
			if (header && content && footer) {
				return $window.innerHeight - (header.offsetHeight + content.offsetHeight + footer.offsetHeight);
			}
		}, function(h) {
			if (h > 0) {
				angular.element($document[0].querySelector('.app-footer')).css({
					'position' : 'absolute'
				});
			} else if (h <= 0) {
				angular.element($document[0].querySelector('.app-footer')).css({
					'position' : 'relative'
				});
			}
		});*/
    $scope.toggleUserbarDropdown = function ($event, item, callback) {
      if (!callback) {
        item.open = !item.open;
        if (item.open) {
          $scope.isUserBarOpen = item.itemCode;
        }
        $event.preventDefault();
        $event.stopPropagation();
      } else {
        if (callback && angular.isString(callback)) {
          callback = ($scope).$eval(callback);
        }
        $scope.isUserBarOpen = false;
        callback(item, $event);
      }
    };
    $scope.userBarOpen = function (item) {
      if ($scope.isUserBarOpen && $scope.isUserBarOpen == item.itemCode) {
        // open is true, will show this menu sub datas
      } else {
        item.open = false;// other sub datas donot show
      }
      return item.open;
    };
    $scope.userBarOpenClick = function () {
      // user sub menu
      if (!$scope.userbarSubMenu) $scope.userbarSubMenu = {};
      if (!$scope.userbarSubMenu.menuStyle) {
        $scope.userbarSubMenu.menuStyle = {
          "itemCode": "MenuStyle",
          "displayName": "Menu Style",
          "icon": "meum",
          "subMenu": {
            "callback": "setMenuStyle",
            "data": { 'false': 'Top', 'true': 'Left' }
          }
        };
      }
      if (!$scope.userbarSubMenu.logout) {
        $scope.userbarSubMenu.logout = {
          "displayName": "logout",
          "icon": "logout",
          "callback": "mainCtrl.exit"
        };
      }
      $scope.isUserBarOpen = false;
    };
    $scope.setMenuStyle = function (isLeft, $event) {
      $scope.app.settings.leftMenu = isLeft == 'true' ? true : false;
      storageService.saveSystemSettings($scope.app.settings);
    }

    ctrl.exit = function () {
      signonService.exit().then(function () {
        log.debug('had signoff');
        $scope.go('signon');
      }, angular.noop);
    };

    $rootScope.$on('$destroy', function () {
      (watcher || angular.noop)();
    });

    function initApplicationSetting() {
      var defaultApp = {
        color: {},
        settings: {
          theme: Constants.THEME_DEFAULT,
          leftMenu: false,
          logLevel: $log.logLevels['*'],
          collapseLeftMenu: false,
          collapseRightAside: false
        }
      };
      $rootScope.app = angular.merge(defaultApp, {
        'settings': storageService.getSystemSettings()
      });
    }

    $rootScope.initLocaleData = function () {
      var defer = $q.defer();
      var userLocalesAjaxService = ajaxServiceFactory.buildAjaxService({
        getUserLocales: {
          url: 'do/user/locales',
          method: 'get'
        }
      });
      userLocalesAjaxService.getUserLocales().then(function (response) {
        var systemInfo = storageService.getSystemInfo();
        var language = storageService.getCookie(systemInfo.LOCALE_COOKIE_NAME) || storageService.getUserInfo().locale || $translate.proposedLanguage() || $translate.resolveClientLocale() || 'en_US';
        $scope.langs = {};
        angular.forEach(response.data, function (userAttribute, index) {
          $scope.langs[userAttribute.uid] = userAttribute.name;
        });
        $scope.I18N.language = $scope.langs[language] ? language : 'en_US';
        $scope.selectLang = $scope.langs[language] || "English";
        if (!$scope.userbarSubMenu) $scope.userbarSubMenu = {};
        if (!$scope.userbarSubMenu.langMenu) {
          // user sub menu
          $scope.userbarSubMenu.langMenu = {
            "itemCode": "LocalChange",
            "displayName": "",
            "icon": "language",
            "subMenu": {
              "callback": "setLang",
              "data": {}
            }
          };
        }
        $scope.userbarSubMenu.langMenu.displayName = $scope.selectLang;
        $scope.userbarSubMenu.langMenu.subMenu.data = $scope.langs;
        // change page locale
        $scope.setLang = function (language, $event) {
          if ($scope.selectLang != $scope.langs[language]) {
            $scope.selectLang = $scope.langs[language];
            $scope.userbarSubMenu.langMenu.displayName = $scope.selectLang;
            $scope.userbarSubMenu.langMenu.subMenu.data = $scope.langs;
            // java session
            var changeLocaleAjaxService = ajaxServiceFactory.buildAjaxService({
              changeLocale: {
                url: 'do/user/locale/' + language,
                method: 'get'
              }
            });
            changeLocaleAjaxService.changeLocale().then(function (response) {
              var stateName = $scope.$state.current.name;
              if (stateName) {
                var url = stateName.split('_');
                if (url.length > 2) {
                  var module = url[0];
                  url = url.slice(-2);
                  url = 'do/' + module + '/resource/' + url.join('/');
                } else if (stateName == 'app_waf_home') {
                  url = 'do/waf/resource/common/home';
                }
                var loadResourceAjaxService = ajaxServiceFactory.buildAjaxService({
                  loadConfig: {
                    'url': url,
                    'method': 'get'
                  }
                });
                loadResourceAjaxService.loadConfig().then(function (response) {
                  var resources = response ? response.data : null;
                  if (resources) {
                    storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
                    storageService.setItemToSession(Constants.SESSION_I18N_VALIDATION_RESOURES, {});
                    $rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE, { 'language': language });
                  }
                });
              }
            });
          }
        };
        defer.resolve();
      });
      return defer.promise;
    }


		/**
		 * $scope.notifications = [ {
				message : 'Notifications One',
				time : '2017/02/20 15:22:30',
			}, {
				message : 'Notifications Two',
				time : '2017/02/20 15:22:30',
			}, {
				message : 'Notifications Three',
				time : '2017/02/20 15:22:30',
			} ];
		 */
    $rootScope.initNotificationData = function () {
      var defer = $q.defer();
      var notificationsAjaxService = ajaxServiceFactory.buildAjaxService({
        getNotifications: {
          url: 'do/cda/deliMessage/notifications',
          method: 'get'
        }
      });
      notificationsAjaxService.getNotifications().then(function (response) {
        $scope.notificationWrap = {};
        $scope.notificationWrap.allNum = response.data.allNum;
        $scope.notificationWrap.notifications = response.data.msgData;
        defer.resolve();
      });
      return defer.promise;
    }
    $scope.notificationItemRedirect = function (notification) {
      $scope.go('cda.deliMessage.view', { deliMessageId: notification.deliMessageId, deliveryFolder: 'R' });
    }
    $scope.notificationListRedirect = function () {
      $scope.go('cda.deliMessage.list');
    }

    $rootScope.updateTheme = function () {
      var siteInfo = storageService.getSiteInfo();
      var theme = siteInfo ? (siteInfo.theme || $rootScope.app.settings.theme) : $rootScope.app.settings.theme;
      routerService.setTheme(theme);
      updateLogo();
    }
    function updateLogo() {
      commonService.getLogo().then(function (response) {
        $rootScope.logo = response;
      });
    };
    $rootScope.auditAndNoteButtons = [{
      "name": "audit",
      "enabled": "!disabledAuditOrNote",
      "tooltip": "label.audit.viewaudit",
      "type": "button",
      "btnClass": "btn-default",
      "options": {
        "icon": "audit",
        "callback": {
          "click": "viewAudit"
        }
      },
      'btnScope': $scope
    }, {
      "name": "note",
      "enabled": "!disabledAuditOrNote",
      "tooltip": "label.note.create",
      "type": "button",
      "btnClass": "btn-default",
      "options": {
        "icon": "note",
        "callback": {
          "click": "createNote"
        }
      },
      'btnScope': $scope
    }];
  }
})(angular);
